package com.example.hadoopdemo.executor.recommend.movie;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 计算推荐结果，优化{@link Step4}，支持分布式
 *
 * @author Ruison
 * @date 2021/12/9
 */
public class Step5 {

    public static class RecommendMapper extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            String[] values = Recommend.DELIMITER.split(value.toString());
            context.write(new Text(values[0]), new Text(values[1] + "," + values[2]));
        }
    }

    /**
     * 矩阵加法
     */
    public static class RecommendReducer extends Reducer<Text, Text, Text, Text> {
        private final static Text v = new Text();

        @Override
        protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            Map<String, Double> result = new HashMap<>(16);
            for (Text value : values) {
                String[] arr = value.toString().split(",");
                if (result.containsKey(arr[0])) {
                    result.put(arr[0], result.get(arr[0]) + Double.parseDouble(arr[1]));
                } else {
                    result.put(arr[0], Double.parseDouble(arr[1]));
                }
            }
            for (Map.Entry<String, Double> entry : result.entrySet()) {
                String itemId = entry.getKey();
                double score = entry.getValue();
                v.set(itemId + "," + score);
                context.write(key, v);
            }
        }
    }
}
